/*///////////////////////////////////////////////////////////////////////////////
-- Author:      liuhx
-- Created:     Wed Nov 28 11:36:25 CST 2018
-- Description:
-- If you have any question,please email to liuhx@gentlesoft.com.cn
////////////////////////////////////////////////////////////////////////////////*/
package com.ctsi.question.controller;

import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilMisc;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.framework.security.util.SecurityUtil;
import com.ctsi.question.entity.Expert;
import com.ctsi.question.entity.Question;
import com.ctsi.question.entity.QuestionQuery;
import com.ctsi.question.service.ExpertService;
import com.ctsi.question.service.QuestionService;
import com.ctsi.question.vo.QuestionLibVo;
import com.ctsi.question.vo.ZhuanJiaIds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Question Controller 类
 *
 * @author liuhx
 * @description Question
 * @created Wed Nov 28 11:36:25 CST 2018
 */
@RestController
public class QuestionController {
    private static final Logger logger = LoggerFactory.getLogger(QuestionController.class);
    @Autowired
    private QuestionService questionService;

    @Autowired
    private VoTemplate voTemplate;

    @Autowired
    private ExpertService expertService;


    /*
     * 当前登陆用户回答问题列表
     * */
    @PostMapping(value = "/question/selectQuLibByLoginId", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<QuestionLibVo>> selectQuLibByLoginId(@RequestBody QuestionQuery ppp) {
        ppp.setUserid(SecurityUtil.getUser().getUserId());
        Page<Question> result = questionService.selectQuLibByLoginId(UtilHttp.filterBlank(UtilMisc.toMap(ppp)), ppp.getStart(), ppp.getPageSize());
        List<QuestionLibVo> questionLibVos = result.getResult().stream().map(lib -> {
            QuestionLibVo questionLibVo = voTemplate.defaultExcute(new QuestionLibVo(), lib);
            questionLibVo.setCreateDateStr(UtilDateTime.longToString(lib.getCreate_date()));
            return questionLibVo;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(), result.getTotalCount(), result.getPageSize(), questionLibVos));
    }

    /*
     * 更新浏览数量
     * method；updateLiuLanNumById、
     *
     * */
    @PostMapping(value = "/question/updateLiuLanNumById", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Long> updateLiuLanNumById(@RequestBody Question question) {
        Integer num = questionService.updateLiuLanNumById(question);
        Long liulannum = question.getLiulannum();
        return UnifiedResponse.ok(liulannum);
    }

    /*
     * 添加或修改问题
     * method:addOrEditQuestion
     * param:Question
     * */
    @PostMapping(value = "/question/addOrEditQuestion", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Integer> addOrEditQuestion(@RequestBody ZhuanJiaIds question) {
        if (UtilValidate.isEmpty(question.getId())) {
            UserInfo user = SecurityUtil.getUser();
            question.setId(UUIDGenerator.getId());
            question.setCreate_date(System.currentTimeMillis());
            question.setIs_default(0);
            question.setLiulannum(Long.valueOf(0));
            question.setPinglunnum(Long.valueOf(0));
            question.setUserid(user.getUserId());
            question.setPostman(user.getFullName());
            question.setDepartment(user.getDepartName());
            int i = questionService.insertQuestion(question);
            String ids = question.getIds();
            if (UtilValidate.isNotEmpty(ids)) {
                List<String> arr = new ArrayList<>();
                if (!ids.contains(",")) {
                    arr.add(ids);
                } else {
                    arr = Arrays.asList(ids.split(","));
                }
                int result = arr.stream().parallel().filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                    try {
                        Expert expert = new Expert();
                        expert.setQuestion_id(question.getId());
                        expert.setId(UUIDGenerator.getId());
                        expert.setUserid(id);
                        expert.setIs_default(0);
                        return this.expertService.insertExpert(expert);
                    } catch (Exception e) {
                        logger.error("{}", e);
                        return 0;
                    }
                }).sum();
            }
            return UnifiedResponse.ok(i);
        } else {
            int i = questionService.updateQuestionById(question);
            return UnifiedResponse.ok(i);
        }
    }

    /*
     * 根据id查询问题详情
     * method:selectQuestionById
     *param:id
     * */
    @PostMapping(value = "/question/selectQuestionById", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<QuestionLibVo> selectQuestionById(@RequestParam("id") String id) {
        if (UtilValidate.isEmpty(id)) {
            return UnifiedResponse.ok(null);
        }
        Question result = questionService.selectQuestionById(id);
        List<String> strings = expertService.selectFullNameById(id);
        Question temp = new Question();
        temp.setId(result.getId());
        temp.setLiulannum(result.getLiulannum() + 1);
        questionService.updateLiuLanNumById(temp);
        result.setLiulannum(result.getLiulannum() + 1);
        QuestionLibVo questionLibVo = voTemplate.defaultExcute(new QuestionLibVo(), result);
        if (UtilValidate.isNotEmpty(strings)) {
            questionLibVo.setFullNameList(strings);
        }
        questionLibVo.setCreateDateStr(UtilDateTime.longToString(result.getCreate_date()));
        return UnifiedResponse.ok(questionLibVo);
    }

    /*
     * 删除问题
     * method:deleteQuestionById
     * param:ids
     * */

    @PostMapping(value = "/question/deleteQuestionById", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<String> deleteQuestionById(@RequestParam("ids") String ids) {
        if (UtilValidate.isNotEmpty(ids)) {
            List<String> arr = new ArrayList<>();
            if (!ids.contains(",")) {
                arr.add(ids);
            } else {
                arr = Arrays.asList(ids.split(","));
            }
            int result = arr.stream().parallel().filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    Question question = new Question();
                    question.setId(id);
                    question.setIs_default(1);
                    return this.questionService.deleteQuestionById(question);
                } catch (Exception e) {
                    logger.error("{}", e);
                    return 0;
                }
            }).sum();
            if (arr.size() > 1) {
                return UnifiedResponse.ok("选中" + arr.size() + "条数据，成功删除" + result + "条数据！");
            } else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return UnifiedResponse.ok("删除成功!");
    }

    /*
     * 多条件查询问题列表
     * method:selectMulitCondition
     * param:QuestionQuery
     * */
    @PostMapping(value = "/question/queryQuestionListById", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<QuestionLibVo>> queryQuestionListById(@RequestBody QuestionQuery ppp) {
        if (UtilValidate.isNotEmpty(ppp.getStartDate())) {
            ppp.setStartDate(String.valueOf(UtilDateTime.toLong(ppp.getStartDate())));
        }
        if (UtilValidate.isNotEmpty(ppp.getEndDate())) {
            ppp.setEndDate(String.valueOf(UtilDateTime.toLong(ppp.getEndDate())));
        }
        Page<Question> result = questionService.selectMulitCondition(UtilHttp.filterBlank(UtilMisc.toMap(ppp)), ppp.getStart(), ppp.getPageSize());
        List<QuestionLibVo> questionLibVos = result.getResult().stream().map(lib -> {
            QuestionLibVo questionLibVo = voTemplate.defaultExcute(new QuestionLibVo(), lib);
            questionLibVo.setCreateDateStr(UtilDateTime.longToString(lib.getCreate_date()));
            return questionLibVo;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(), result.getTotalCount(), result.getPageSize(), questionLibVos));
    }

    /*
     * 当前登陆用户所提问题列表
     * method:selectMulitCondition
     * param:QuestionQuery
     * */
    @PostMapping(value = "/question/queryQuestionListByUserId", consumes = "application/json", produces = "application/json;charset=UTF-8")
    @ResponseStatus(HttpStatus.OK)
    public UnifiedResponse<Page<QuestionLibVo>> queryQuestionListByUserId(@RequestBody QuestionQuery ppp) {
        if (UtilValidate.isNotEmpty(ppp.getStartDate())) {
            ppp.setStartDate(String.valueOf(UtilDateTime.toLong(ppp.getStartDate())));
        }
        if (UtilValidate.isNotEmpty(ppp.getEndDate())) {
            ppp.setEndDate(String.valueOf(UtilDateTime.toLong(ppp.getEndDate())));
        }
        ppp.setUserid(SecurityUtil.getUser().getUserId());
        Page<Question> result = questionService.queryQuestionListByUserId(UtilHttp.filterBlank(UtilMisc.toMap(ppp)), ppp.getStart(), ppp.getPageSize());
        List<QuestionLibVo> questionLibVos = result.getResult().stream().map(lib -> {
            QuestionLibVo questionLibVo = voTemplate.defaultExcute(new QuestionLibVo(), lib);
            questionLibVo.setCreateDateStr(UtilDateTime.longToString(lib.getCreate_date()));
            return questionLibVo;
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(new Page<>(ppp.getStart(), result.getTotalCount(), result.getPageSize(), questionLibVos));
    }

}
